package org.jbfilter.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;

public class _JbFilterDateUtils {
	
	public static final String DEFAULT_PATTERN = "dd/MM/yyyy";
	
	private static final ThreadLocal<_ThreadLocalContainer> TL_FOR_THREAD_LOCAL_CONTAINER = 
		new ThreadLocal<_ThreadLocalContainer>() {
			@Override
			protected _ThreadLocalContainer initialValue() {
				return new _ThreadLocalContainer();
			}
		};

	/**
	 * The last millisecond of the passed in day.
	 * For instance if date is 23/04/2009 12:46, 23/04/2009 23:59:59:0999 is returned.
	 * @param date a day (object won't be modified)
	 * @return a different object according to the contract 
	 */
	public static Date getLastMillisecondOfDay(Date date) {
		date = DateUtils.truncate(date, Calendar.DAY_OF_MONTH);
		date = DateUtils.addDays(date, 1);
		date = DateUtils.addMilliseconds(date, -1);
		return date;
	}

	public static SimpleDateFormat getSimpleDateFormat(String pattern) {
		return TL_FOR_THREAD_LOCAL_CONTAINER.get().getSimpleDateFormat(pattern);
	}

	public static String dateToStringNullSafe(Date date, DateFormat dateFormat) {
		if (date == null) {
			return null;
		}
		return dateFormat.format(date);
	}
	/**
     * Adds to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param calendarField  the calendar field to add to
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public static Date add(Date date, int calendarField, int amount) {
        if (date == null) {
            throw new IllegalArgumentException("The date must not be null");
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(calendarField, amount);
        return c.getTime();
    }

}
